//
//  GDRequestSender.m
//  GDNetworkLayer
//
//  Created by hexuan on 2017/6/2.
//  Copyright © 2017年 hexuan. All rights reserved.
//

#import "GDRequestSender.h"
#import <AFNetworking/AFNetworking.h>
#import "GDBaseRequest.h"

#define kBaseUrl @"http://10.207.141.213/GDInterface/"

@interface GDRequestSender()

@property (nonatomic,copy)NSString *status;
@property (nonatomic,copy)NSString *errorMessage;

@end

@implementation GDRequestSender {
    GDBaseRequest *request;
}

+ (Class) requestClass {
    return nil;
}

+ (NSString *)path {
    return nil;
}

- (instancetype)init {
    if (self = [super init]) {
        request = [[[self class] requestClass] new];
    }
    return self;
}

- (void)sendRequestWithSuccess:(success)success failure:(failure)failure {
    NSString *paraErrorMsg = [self paraErrorMsg];
    if (paraErrorMsg.length != 0) {
        if (failure) {
            failure([self paraErrorMsg]);
        }
        return;
    }
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/html", @"application/x-www-form-urlencoded", @"text/javascript", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = responseSerializer;
    NSString *fullPath = [kBaseUrl stringByAppendingString:[[self class] path]];
    [manager POST:fullPath parameters:[request toDictionary]
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              [self updatePropertyWithDic:responseObject];
              [self sendRequestDidSuccess];
              if (success) {
                  success();
              }
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              if (failure) {
                  failure(error.localizedDescription);
              }
          }];
}

- (void)updatePropertyWithDic:(NSDictionary *)dic {
    for (NSString *key in [dic allKeys]) {
        id value = [dic objectForKey:key];
        if ([key isEqualToString:@"data"]) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            [super updatePropertyWithDic:dataDic];
        }
        else {
            [self setValue:value forKey:key];
        }
    }
}

- (NSString *)paraErrorMsg{
    return nil;
}

- (void)sendRequestDidSuccess {
    
}

@end
